<template>
  <div>
    <!-- 表格部分 -->
    <el-card style="margin-top: 10px">
      <div style="margin-bottom: 5px">
        <el-button type="primary" plain size="small" @click="onAdd"
          ><el-icon><DocumentAdd /></el-icon>添加</el-button
        >
      </div>
      <el-table :data="tableData" style="width: 100%">
        <el-table-column type="index" label="序号" width="100">
          <template #default="{ $index }">
            {{ $index + 1 }}
          </template></el-table-column
        >
        <el-table-column prop="name" label="名称" />
        <el-table-column
          prop="time"
          label="时间"
          sortable
          :sort-orders="['descending', 'ascending']"
        >
          <template #default="{ row }">
            {{ dayjs(row.create_date).format('YYYY-MM-DD HH:mm:ss') }}
          </template>
        </el-table-column>
        <el-table-column label="操作选项">
          <template #default="{ row }">
            <el-button
              link
              plain
              type="primary"
              size="small"
              @click="onPreview(row)"
              ><el-icon><View /></el-icon>查看</el-button
            >
            <el-button
              link
              plain
              type="primary"
              size="small"
              @click="onRevocation(row)"
              ><el-icon><Delete /></el-icon>删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 弹窗部分 -->
    <el-dialog
      v-model="addDialogVisible"
      :title="title"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @close="onReset(addRuleFormRef)"
      width="30%"
    >
      <el-form
        ref="addRuleFormRef"
        style="max-width: 450px"
        :model="addRuleForm"
        :rules="addRules"
        label-width="80"
        class="demo-ruleForm"
        status-icon
        @submit.prevent
      >
        <el-form-item
          label="名称"
          prop="name"
          name="name"
          required
          style="width: 300px"
        >
          <el-input
            v-model="addRuleForm.name"
            placeholder="请输入名称"
            clearable
            :disabled  = !!imageUrl
          />
        </el-form-item>

        <el-form-item label="上传图片" prop="fileList" name="fileList">
          <el-upload
            v-model:file-list="addRuleForm.fileList"
            class="upload-demo"
            :class="{ 'hide-upload-btn': addRuleForm.fileList.length >= 1 }"
            action="#"
            :accept="accept"
            :auto-upload="false"
            list-type="picture-card"
            :limit="1"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :on-change="beforeUpload"
            :on-exceed="handleExceed"
            :disabled  = !!imageUrl
          >
            <template #trigger>
              <el-icon v-if="addRuleForm.fileList.length < 1 && !imageUrl"
                ><Plus
              /></el-icon>
              <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="onReset(addRuleFormRef)" v-if="!imageUrl"
            >取 消</el-button
          >
          <el-button
            type="primary"
            @click="onSubmit(addRuleFormRef)"
            v-if="!imageUrl"
            >提 交</el-button
          >
          <el-button type="primary" @click="onReset(addRuleFormRef)" v-if="imageUrl"
            >关 闭</el-button
          >
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="pictureDialogVisible">
      <img w-full style="width: 100%" :src="dialogImageUrl" alt="查看图片" />
    </el-dialog>
  </div>
</template>

<script  setup>
import { ref, reactive, onMounted } from 'vue'
import { useStore } from 'vuex'
import { ElMessage, ElMessageBox, dayjs } from 'element-plus'

import {
  getAllPic,
  uploadPic,
  delPic,
  previewPic
} from '@/api/carousel/index.js'

const store = useStore()
const userId = store.state.app.user.id
const addDialogVisible = ref(false)
const addRuleFormRef = ref()
const title = ref('添加')
const accept = ref('.jpg,.png,.jpeg')
const pictureDialogVisible = ref(false)
const dialogImageUrl = ref('')
const imageUrl = ref('')
// 添加表单的内容
const addRuleForm = ref({
  name: '',
  username: '',
  fileList: []
})
const tableData = ref([])

// 校验规则
const addRules = reactive({
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }]
})

onMounted(() => {
  getList()
})

const getList = async () => {
  const res = await getAllPic()
  tableData.value = res.data
}
// 增加
const onAdd = () => {
  if (tableData.value.length >= 5) {
    return ElMessage.error('最多只能添加5条数据，请删除数据之后再添加')
  }
  title.value = '添加'
  addDialogVisible.value = true
}
// 删除一条
const onRevocation = (row) => {
  ElMessageBox.confirm('您确定要删除这条数据吗？', '系统提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      const res = await delPic([row.uuid])
      ElMessage.success(res.message)
      getList()
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除'
      })
    })
}

// 文件预览
const handlePreview = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url
  pictureDialogVisible.value = true
}
// 文件删除
const handleRemove = (file, uploadFiles) => {
  console.log(file, uploadFiles)
}

const beforeUpload = (file) => {
  console.log('file', file)

  const typeArray = accept.value.split(',') || []
  const type = file.name.substring(file.name.lastIndexOf('.'))
  addRuleForm.value.fileList.push(file)
  if (!typeArray.includes(type)) {
    ElMessage.error(`只能上传${accept.value}格式的文件`)
    addRuleForm.value.fileList = []
    return false
  }
  if (file.size / 1024 / 1024 > 500) {
    ElMessage.error('文件大小不能超过500M')
    addRuleForm.value.fileList = []
    return false
  }
}

// 文件超出限制时触发
const handleExceed = (files, fileList) => {
  addRuleForm.value.fileList = [files[0]]
}

// 提交
const onSubmit = async (formEl) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (addRuleForm.value.fileList.length === 0) {
        return ElMessage.error('请选择文件')
      }
      const formData = new FormData()
      addRuleForm.value.fileList.forEach(async (file) => {
        if (file.raw) {
          formData.append('file', file.raw)
          formData.append('filename', addRuleForm.value.name)
          formData.append('userId', userId)
        }
        const res = await uploadPic(formData)
        ElMessage.success(res.message)
        getList()
        addDialogVisible.value = false
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}
// 重置
const onReset = (formEl) => {
  addRuleForm.value = {
    name: '',
    username: '',
    fileList: []
  }
  formEl.resetFields()
  addDialogVisible.value = false
  imageUrl.value = ''
}

// 查看
const onPreview = async (row) => {
  title.value = '预览'
  const res = await previewPic(row.path)
  addRuleForm.value.name = row.name
  imageUrl.value = 'data:image/png;base64,' + res.data
  addDialogVisible.value = true
}
</script>

<style lang="scss" scoped>
.avatar{
  width: 148px;
  height: 148px;
  display: block;
}
:deep(.hide-upload-btn .el-upload--picture-card) {
  display: none;
}
:deep(.el-table .el-table__header-wrapper th) {
  word-break: break-word;
  background-color: #f8f8f9 !important;
  color: #515a6e;
  height: 40px !important;
  font-size: 13px;
}

:deep(.el-form .el-form-item .el-form-item__label) {
  font-weight: bold !important;
}

:deep(.el-form .el-form-item .second_label .el-form-item__label) {
  font-weight: bold !important;
}
:deep(.second_label .el-form-item__error) {
  position: static !important;
}
.buttons {
  text-align: center;
}
</style>
